package com.achievo.know.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;

import com.dayatang.domain.BaseEntity;
import com.dayatang.domain.InstanceFactory;

/**
 * 帐户
 * 
 * @author chencao
 * 
 */
@Entity
@Table(name = "RAMS_USER")
public class User extends BaseEntity {

	/**
	 * 
	 */
	private static final long serialVersionUID = -321590260221566017L;

	// 账户名
	@NotNull
	//@Pattern(regexp="^\\w{2,}$", message="username not match pattern")
	@Column(name = "USERNAME", length = 25, nullable = false,unique=true)
	
	private String username;

	// 密码
	@Column(name = "PASSWORD", length = 50)
	private String password;

	// 真实姓名
	@Column(name = "REAL_NAME")
	private String realName;

	// 电子邮件
	@Column(name = "EMAIL", length = 50)
	private String email;

	// 注册日期
	@NotNull
	@Column(name = "REGISTRY_DATE", nullable = false)
	@Temporal(TemporalType.TIMESTAMP)
	private Date registryDate;

	// 是否被锁定
	@NotNull
	@Column(name = "IS_LOCKED", nullable = false)
	private Boolean locked;

	// 最后的密码修改日期
	@Column(name = "PASSWORD_LAST_UPDATE_DATE")
	@Temporal(TemporalType.TIMESTAMP)
	private Date passwordLastUpdateDate;

	// 描述
	@Column(name = "DESCRIPTION", length = 1000)
	private String description;
	
	//是否访客
	@Column(name = "IS_LOCAL")
	private boolean isLocal;

	@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) 
	@JoinTable(name = "RAMS_USER_R_ROLE", joinColumns = { @JoinColumn(name = "USER_ID",referencedColumnName="id") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID",referencedColumnName="id") })
	@OrderBy(value="id")
	private Set<Role> roles = new HashSet<Role>();
	
	//用户的目录权限
	@ManyToMany
	@JoinTable(name="RAMS_USER_R_CATEGORY", joinColumns={@JoinColumn(name = "USER_ID") },inverseJoinColumns={@JoinColumn(name = "CATEGORY_ID")})
	@OrderBy(value="position")
	private Set<Category> categorys=new HashSet<Category>();
	
	// 部门
	@Column(name = "DEPT", length = 100)
	private String deptment;
	
	public String getRolesStr(){
		StringBuilder b=new StringBuilder();
		Iterator<Role> i= roles.iterator();
		while(i.hasNext()){
			b.append(i.next().getName()).append(",");
		}
		if(b.length()>0)
			b.deleteCharAt(b.length()-1);
		return b.toString();
	}
	

	public String getDeptment() {
		return deptment;
	}


	public void setDeptment(String deptment) {
		this.deptment = deptment;
	}


	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Date getRegistryDate() {
		return registryDate;
	}

	public void setRegistryDate(Date registryDate) {
		this.registryDate = registryDate;
	}

	public Boolean getLocked() {
		return locked;
	}

	public void setLocked(Boolean locked) {
		this.locked = locked;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Date getPasswordLastUpdateDate() {
		return passwordLastUpdateDate;
	}

	public void setPasswordLastUpdateDate(Date passwordLastUpdateDate) {
		this.passwordLastUpdateDate = passwordLastUpdateDate;
	}
	
	

	public boolean isLocal() {
		return isLocal;
	}

	public void setLocal(boolean isLocal) {
		this.isLocal = isLocal;
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	

	public Set<Category> getCategorys() {
		return categorys;
	}

	public void setCategorys(Set<Category> categorys) {
		this.categorys = categorys;
	}

	@Override
	public boolean equals(Object arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * lingen.liu 仓储
	 */
	private static UserRepository userRepository;

	public static UserRepository getUserRepository() {
		if (userRepository == null) {
			userRepository = InstanceFactory
					.getInstance(UserRepository.class);
		}
		return userRepository;
	}

	public static void setUserRepositoryRepository(
			UserRepository accountRepository) {
		User.userRepository = accountRepository;
	}

	/**/// ////////////////////领域行为 start/////////////////////////////*/

	/**
	 * 新增帐户
	 */
	public void add() {
		this.setLocked(false);
		this.setRegistryDate(new Date());
		this.setPasswordLastUpdateDate(new Date());
		getUserRepository().save(this);
	}

	/**
	 * 删除帐户
	 */
	public void remove() {
	    this.setRoles(null);
	    update();
	    getUserRepository().remove(this);
	}

	/**
	 * 更新一个帐户
	 */
	public void update() {
		getUserRepository().save(this);
	}

	/**
	 * 锁定帐户
	 */
	public void disabled() {
		if (this.getLocked() != true) {
			this.setLocked(true);
			getUserRepository().save(this);
		}
	}

	/**
	 * 解锁帐户
	 */
	public void enabled() {
		if (this.getLocked() != false) {
			this.setLocked(false);
			getUserRepository().save(this);
		}
	}

	/**
	 * 通过Id获取一个帐号
	 * @param id
	 * @return
	 */
	public static User get(Long id){
		return getUserRepository().get(id);
	}
	
	/**
	 * 检测是否已存在当前邮箱
	 * @return
	 */
	public static boolean isEmailExist(String email){
		return getUserRepository().isEmailExist(email);
	}
	
	/**
	 * 检测是否存在当前用户名
	 * @return
	 */
	public static boolean isUsernameExist(String username){
		return getUserRepository().isUsernameExist(username);
	}
	/**
	 * 根据用户名获取帐号信息
	 * @param username
	 * @return
	 */
	public static User get(String username){
		return getUserRepository().get(username);
	}
}
